package com.ebao.service.base.impl;

import java.io.Serializable;
import java.util.List;

import com.ebao.dao.base.IBaseJpaDao;
import com.ebao.service.base.ICrudService;
import com.ebao.util.PageResult;

/**
 * @author snow
 * @date 2012-6-23
 * @param <P>
 */
public class CrudServiceImpl<P> implements ICrudService<P> {
	
	protected IBaseJpaDao<P> dao;
	
	public void setDao(IBaseJpaDao<P> dao) {
        this.dao = dao;
    }
	
	public void save(P obj) {
		dao.save(obj);
	}

	public void update(P obj) {
		dao.update(obj);
	}

	public void delete(P obj) {
		dao.delete(obj);
	}

	public void deleteById(Serializable id) {
		if(id != null && !id.equals("")){
			dao.deleteById(id);
		}
	}

	public P getById(Serializable id) {
		return dao.getById(id);
	}
	
	public P getByJpql(String jpql, Object...objs){
		return dao.getByJpql(jpql, objs);
	}
	
	public List<P> getByJpqlAfterWhere(String jpql, int currentPage, int pageSize, Object... objs){
		return dao.queryByPageAfterWhere(jpql, (currentPage - 1) * pageSize, pageSize, objs);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PageResult<P> getPageByJpqlAfterWhere(String jpql, int currentPage, int pageSize, Object... objs) {
		PageResult pageResult = new PageResult();
		
		List<P> contents = dao.queryByPageAfterWhere(jpql, (currentPage - 1) * pageSize, pageSize, objs);
		pageResult.setContents(contents);
		pageResult.setCurrentPage(currentPage);
		pageResult.setPageSize(pageSize);
		pageResult.setTotalCount(dao.getCount(jpql, objs));
		
		return pageResult;
	}
	
	public int executeJpql(String jpql, Object... objs){
		return dao.batchUpdate(jpql, objs);
	}

	public int getCount(String jpql, Object... objs) {
		return dao.getCount(jpql, objs);
	}

}
